<!-- eslint-disable vue/multi-word-component-names -->
<script setup lang="ts">
import type { LoginRequestData } from './apis/type'
import { loginApi, getCaptcha } from './apis'
import { type FormInstance, type FormRules } from 'element-plus'
// import { useFocus } from './composables/useFocus'
import { reactive, ref } from 'vue'
import { Key, Loading, Lock, Picture, User } from '@element-plus/icons-vue'
import { useUserStore } from '@/pinia/stores/user'
import { useRouter } from 'vue-router'

const router = useRouter()

const userStore = useUserStore()

// const { isFocus, handleBlur, handleFocus } = useFocus()

// 登录表单元素的引用
const loginFormRef = ref<FormInstance | null>(null)

// 登录按钮，点击显示加载中图标
const loading = ref(false)

/** 验证码图片 URL */
const codeUrl = ref('')

// 登录表单数据
const loginFormData: LoginRequestData = reactive({
  username: 'userAdmin',
  password: '123456789',
  code: '',
})

// 登录表单校验规则
const loginFormRules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 16, message: '长度在 8 到 16 个字符', trigger: 'blur' },
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
}

const handleLogin = () => {
  loginFormRef.value?.validate((valid) => {
    if (!valid) {
      console.log(1)

      ElMessage.error('表单填写有误')
      return
    }
    // 判断验证码是否正确，此处为图片验证码，默认为v3admin，业务中根据实际情况调整

    if (!(loginFormData.code.toLowerCase() === 'v3admin')) {
      ElMessage.error('验证码错误')
      return
    }

    loading.value = true
    loginApi(loginFormData)
      .then(({ data }) => {
        console.log(data)
        userStore.ISetToken(data.token)
        router.push('/')
      })
      .catch(() => {
        // 当登录失败时，重新生成验证码
        createCode()
        loginFormData.password = ''
      })
      .finally(() => {
        loading.value = false
      })
  })
}

// 创建验证码
const createCode = () => {
  // 清空已输入的验证码
  loginFormData.code = ''
  // 清空图片路径
  codeUrl.value = ''
  // 获取验证码
  getCaptcha().then((res) => {
    codeUrl.value = res.data
  })
}

// 初始化验证码
createCode()
</script>

<template>
  <div class="login-container">
    <!-- 主题设置 -->

    <!-- 登陆界面的猫头鹰显示 -->

    <!-- 登录卡片 -->
    <div class="login-card">
      <div class="title">
        <img src="../../common/assets/images/layouts/logo-text-2.png" alt="" />
      </div>
      <div class="content">
        <el-form
          ref="loginFormRef"
          :model="loginFormData"
          :rules="loginFormRules"
          @keyup.enter="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
              v-model.trim="loginFormData.username"
              type="text"
              placeholder="用户名"
              tabindex="1"
              size="large"
              :prefix-icon="User"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model.trim="loginFormData.password"
              placeholder="密码"
              type="password"
              tabindex="2"
              :prefix-icon="Lock"
              size="large"
              show-password
            >
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              v-model.trim="loginFormData.code"
              placeholder="验证码"
              type="text"
              tabindex="3"
              :prefix-icon="Key"
            >
              <template #append>
                <el-image :src="codeUrl" draggable="false" @click="createCode">
                  <!-- 定义占位内容 -->
                  <template #placeholder>
                    <el-icon>
                      <Picture />
                    </el-icon>
                  </template>
                  <!-- 加载失败显示图片 -->
                  <template #error>
                    <el-icon>
                      <Loading />
                    </el-icon>
                  </template>
                </el-image>
              </template>
            </el-input>
          </el-form-item>
          <!-- .prevent用于阻止事件的默认行为，例如点击<a>后会跳转页面，<form> 提交后会刷新页面 -->
          <el-button
            :loading="loading"
            type="primary"
            size="large"
            @click.prevent="handleLogin"
          >
            登 录
          </el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100%;

  .login-card {
    width: 480px;
    max-width: 90%;
    border-radius: 20px;
    box-shadow: 0 0 10px #dcdfe6;
    background-color: var(--el-bg-color);
    overflow: hidden;

    .title {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 150px;
      img {
        height: 100%;
      }
    }

    .content {
      display: flex;
      flex-direction: column;
      padding: 10px 50px 50px 50px;

      // :deep穿透组件
      :deep(.el-input-group__append) {
        padding: 0;
        overflow: hidden;
        .el-image {
          display: flex;
          width: 100px;
          height: 40px;
          justify-content: center;
          align-items: center;
        }
      }

      .el-button {
        width: 100%;
        margin-top: 10px;
      }
    }
  }
}
</style>
